package com.mall.czlr.base.controller;

import com.mall.czlr.base.common.Const;
import com.mall.czlr.base.entity.UserContext;
import com.mall.czlr.base.exception.BaseException;
import com.mall.czlr.base.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;

public class BaseController {
    private final HttpServletRequest httpServletRequest;

    @Autowired
    public BaseController(HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }

    @Nullable
    protected UserContext getUserContext() {
        Object userContext = this.httpServletRequest.getAttribute(Const.REQUEST_ATTR_KEY_USER_CONTEXT);
        if (!(userContext instanceof UserContext)) {
            Assert.exception(BaseException.ERROR_IN_INTERCEPTOR, "请求转换错误");
        }

        return (UserContext) userContext;
    }
}
